var Preloader = {
	_imgs : [],
	_loaded : [],
	_callback : function() {
	},
	
	start : function(imgs, callback) {
		this._imgs = imgs;
		this._callback = callback;

		var self = this;
		$(self._imgs).each(function(k, item) {
			$('<img />').attr('src', 'img/' + item).load(function() {
				self._loaded.push(this);
				if (self._loaded.length == self._imgs.length)
					self._callback();
			});
		});
	},
	
	getImg : function(src) {
		for ( var i = 0; i < this._loaded.length; i++) {
			if (this._loaded[i].src.indexOf(src) != -1)
				return this._loaded[i];
		}
	}
};

var Quene = {
	_quenes : {},
	add : function(name, obj, func, delay) {
		this._quenes[name] = this._quenes[name] || [];
		this._quenes[name].push([obj, func, delay]);
		if (this._quenes[name].length==1)
			this.callNext(name);
	},
	callNext : function(name) {
		setTimeout(function(){
				var fun = Quene._quenes[name].shift();
				//console.log(name,fun);
				if (Quene._quenes[name].length>0)
					Quene.callNext(name);
				if (fun)
					fun[1].apply(fun[0]);
		}, Quene._quenes[name][0][2]);
	}
};

var AdminPanel = {
	element : null,
	init : function() {
		this.element = $('#adminPanel');
	}
}

$(function() {
	AdminPanel.init();
	
	Preloader.start([ 'cards.png', 'card-back.png', 'avatars.png', 'noise.png'], Game.init);
	
	Quene.add('game',null,function(){Table.addPlayer(1, 'Pierwszy', 123, 'M')}, 100);
	Quene.add('game',null,function(){Table.addPlayer(2, 'drugi', 234, 'M')}, 100);
	Quene.add('game',null,function(){Table.addPlayer(3, 'trzeci', 345, 'M')}, 100);
	Quene.add('game',null,function(){Table.addPlayer(4, 'czwarty', 456, 'M')}, 100);
	Quene.add('game',null,function(){Table.addPlayer(5, 'piąty', 7890, 'M')}, 100);

	function game() {
		if (Table.currentPlayer==Table.players.length-1) 
			setTimeout(function(){ Table.startPlayerTurn(); game();}, 2000);
		else
			setTimeout(function(){ Table.startPlayerTurn(); game();}, 1000);
		
	}
	//setTimeout(function(){ game(); }, 2000);
	
});

$(window).resize(Table.onResize);